package com.situ.mall.controller.back;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.situ.mall.common.ServerResponse;
import com.situ.mall.util.ImageServerUtil;
import com.situ.mall.util.ImageServerUtil.EnumImageServer;
import com.situ.mall.util.QiniuUtil;

@RequestMapping("/upload")
@Controller
public class UploadController {

	@RequestMapping("/uploadImg")
	@ResponseBody
	public ServerResponse uploadImg(MultipartFile file) {
		String fileName = upload(file);
		
		return ServerResponse.createSuccess("上传成功", fileName);
	}

	
	
	@RequestMapping("/uploadImgByEditor")
	@ResponseBody
	public Map<String, Object> uploadImgByEditor(MultipartFile file) {
		String fileName = upload(file);
		
		//浏览器可以访问的地址，这个才是返回给Editor
		// http://localhost:8080/pic/479e2bba8d934c7bbe69baf7d424a965.png
		String url = ImageServerUtil.getImageFullUrl(fileName);
		
		Map<String, Object> map = new HashMap<>();
		map.put("error", 0);
		map.put("msg", "上传成功");
		map.put("url", url);
		
		return map;
	}
	
	/**
	 * 返回上传文件的文件名601b632f4d244071b5f4c581203605d8.png
	 * @param file
	 * @return
	 * @throws IOException 
	 */
	public String upload(MultipartFile file) {
		if (ImageServerUtil.IMG_SERVER == EnumImageServer.QINIU) {
			try {
				return QiniuUtil.uploadImage(file.getBytes());
			} catch (IOException e) {
				e.printStackTrace();
			}
			return "";
		} else {// 上传到本地
			return uploadToLocal(file);
		}
	}

	public String uploadToLocal(MultipartFile file) {
		//为了防止文件重名（重名文件会覆盖丢失），所以生成一个不重复的随机的名字
		//cbbd8d0a-4930-4b0e-8d08-249ba2917b8a
		//601b632f4d244071b5f4c581203605d8
		String name = UUID.randomUUID().toString().replace("-", "");
		// jpg、png
		String extension = FilenameUtils.getExtension(file.getOriginalFilename());
		// 601b632f4d244071b5f4c581203605d8.png
		String fileName = name + "." + extension;
		//把文件保存到d:\pic
		String filePath = "D:\\pic\\" + fileName;
		try {
			file.transferTo(new File(filePath));
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return fileName;
	}
	
	public static void main(String[] args) {
		String name = UUID.randomUUID().toString().replace("-", "");
		System.out.println(name);
	}
}
